package com.sdk.springbootdapr.controller;

import io.dapr.client.DaprClient;
import io.dapr.client.domain.State;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

@RestController
@Slf4j
public class DaprStateController {
    private final DaprClient daprClient;
    private static final String STATE_STORE_NAME = "statestore";

    public DaprStateController(DaprClient daprClient) {
        this.daprClient = daprClient;
    }

    @GetMapping("testState")
    public void testState() {
        // 使用Dapr SDK保存和获取状态
        List<State<?>> states = new ArrayList<>();

        Integer orderId = new Random().nextInt(100);
        HashMap<String, String> metadata1 = new HashMap<>();
        metadata1.put("ttlInSeconds", "100");
        State<Integer> state1 = new State<>("order_1", orderId, null, metadata1, null);
        states.add(state1);

        Integer orderId2 = new Random().nextInt(100);
        HashMap<String, String> metadata2 = new HashMap<>();
        metadata2.put("ttlInSeconds", "10");
        State<Integer> state2 = new State<>("order_2", orderId2, null, metadata2, null);
        states.add(state2);

        daprClient.saveBulkState(STATE_STORE_NAME, states).block();

        Mono<State<Integer>> result = daprClient.getState(STATE_STORE_NAME, "order_1", Integer.class);
        result.blockOptional().ifPresent(state -> {
            log.info("获取后的结果" + state.getValue());
        });
    }


}
